# -*- coding:UTF-8 -*-
import ctypes
import datetime
import os
import sys
import threading
import time

import requests
import win32con
from PyQt5.QtWidgets import QApplication, QMainWindow
from win32process import ResumeThread, SuspendThread

import Audbox_rc
from module import a_sfkuaidi, b_sfkuaidi, c_fsfkuaidi, d_fsfkuaidi, e_tianyancha
from Ui_Audbox import *
from Ui_dialog import *

version = 'v1.1'
Now_Path = os.path.abspath(os.curdir)
Now_Time = datetime.datetime.strftime(datetime.datetime.now(), '%Y%m%d_%H-%M-%S')

class EmittingStream(QtCore.QObject):  # 重定向
    textWritten = QtCore.pyqtSignal(str)
    def write(self, text):
        self.textWritten.emit(str(text))

class MyWindows(QMainWindow): # 单继承主窗体
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_mainWindow()
        self.ui.setupUi(self)
        self.but_connect()
        self.sender = ''
        r = requests.get("https://gitee.com/wwwwwc/audbox/raw/master/version.md").text
        self.lock_status = r.split('@')[1]
        self.zuix_version = r.split('@')[0]
        self.check_lock() # 检测上锁
        self.checkupdate() # 检测更新
        # Install the custom output stream 重定向
        sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)  # test

    def check_lock(self): # 检测上锁
        if self.lock_status != 'unlock':
            self.statusBar().showMessage('程序暂时无法使用')
            self.ui.centralwidget.setEnabled(False) # 锁定控件

    def checkupdate(self): # 检测更新
        if self.lock_status == 'unlock' and self.zuix_version != version:
            msg='提示：最新版本审计工具箱版本为【{}】,您可以在菜单栏更新版本！'.format(self.zuix_version)
            self.statusBar().showMessage(msg)

    def setup_firefox(self): # action 安装火狐
        dialog.setGeometry(QtCore.QRect(self.x()+50, self.y()+100, 500, 80))
        dialog.resize(600, 80)
        dialog.ui1.label.setGeometry(QtCore.QRect(0, 0, 600, 80))
        dialog.setWindowTitle('安装火狐浏览器 @效率视界')
        url = 'https://wwcheng.lanzous.com/b00tvjpvg'
        text = '火狐浏览器V68.0.1 下载地址：<a href="{}">{}</a>'.format(url,url)
        dialog.ui1.label.setText(text)
        dialog.ui1.label.setOpenExternalLinks(True)
        dialog.show()

    def jiaocheng(self): # action 使用教程
        dialog.setGeometry(QtCore.QRect(self.x()+50, self.y()+100, 500, 80))
        dialog.resize(450, 80)
        dialog.ui1.label.setGeometry(QtCore.QRect(0, 0, 450, 80))
        dialog.setWindowTitle('使用教程 @效率视界')
        url = 'https://gitee.com/wwwwwc/audbox'
        text = '码云Gitee使用教程：<a href="{}">{}</a>'.format(url,url)
        dialog.ui1.label.setText(text)
        dialog.ui1.label.setOpenExternalLinks(True)
        dialog.show()

    def upadte_box(self): # action 更新软件
        dialog.setGeometry(QtCore.QRect(self.x()+50, self.y()+100, 500, 80))
        dialog.resize(480, 100)
        dialog.ui1.label.setGeometry(QtCore.QRect(0, 0, 480, 100))
        dialog.setWindowTitle('版本更新 @效率视界')
        url = 'https://gitee.com/wwwwwc/audbox/releases'
        text = '最新版本审计工具箱版本为【{}】<br><br>下载地址：<a href="{}">{}</a><br><br>直接关闭可忽略更新!'.format(self.zuix_version,url,url)
        dialog.ui1.label.setText(text)
        dialog.ui1.label.setOpenExternalLinks(True)
        dialog.show()

    def show_gxh(self): # action 关于软件
        dialog.setGeometry(QtCore.QRect(self.x()+50, self.y()+100, 500, 80))
        dialog.resize(438, 201)
        dialog.ui1.label.setGeometry(QtCore.QRect(0, 0, 441, 201))
        dialog.ui1.label.setPixmap(QtGui.QPixmap(":/logo/icons/12_gongzhonghao.png"))
        dialog.show()
    
    def show_kjz(self): # action 空间站
        dialog.setGeometry(QtCore.QRect(self.x()+50, self.y()+100, 500, 80))
        dialog.resize(400, 80)
        dialog.ui1.label.setGeometry(QtCore.QRect(0, 0,400, 80))
        dialog.setWindowTitle('One Piece @效率视界')
        url = 'http://xiaolv.ys168.com/'
        text = '效率视界的空间站：<a href="{}">{}</a>'.format(url,url)
        dialog.ui1.label.setText(text)
        dialog.ui1.label.setOpenExternalLinks(True)
        dialog.show()
    
    def show_chat(self): # action 群聊
        dialog.setGeometry(QtCore.QRect(self.x()+50, self.y()+100, 500, 80))
        
        dialog.resize(500, 80)
        dialog.ui1.label.setGeometry(QtCore.QRect(0, 0, 500, 80))
        dialog.setWindowTitle('交流提问 @效率视界')
        url = 'https://mp.weixin.qq.com/s/krk_vWtvCZDLepb_KxeGdg'
        text = '效率社群：<a href="{}">{}</a>'.format(url,url)
        dialog.ui1.label.setText(text)
        dialog.ui1.label.setOpenExternalLinks(True)
        dialog.show()

    def normalOutputWritten(self, text):  # 重定向
        # content =(',').join([self.Now_Time(),self.sender]) # 给返回的日志加一个时间戳
        """Append text to the QTextEdit."""
        cursor = self.ui.textBrowser.textCursor()
        cursor.movePosition(QtGui.QTextCursor.End)
        cursor.insertText(text)
        self.__log_text(text)
        self.ui.textBrowser.setTextCursor(cursor)
        self.ui.textBrowser.ensureCursorVisible()

    def __log_text(self,text): # 日志模块
        try:
            path = Now_Path + r'\Log\审计工具箱_{}.log'.format(Now_Time)
            f = open(path, 'a')
            f.write(text)
            f.close()
        except:
            pass

    def paintEvent(self, e):  # 窗口重绘事件,用于自动调整textBrowser
        widget_w = self.ui.centralwidget.width()-20
        widget_h = self.ui.centralwidget.height()-90
        widget_h_margin = self.ui.textBrowser.y()
        top_margin = self.ui.textBrowser.x()
        self.ui.textBrowser.setGeometry(QtCore.QRect(top_margin, widget_h_margin, widget_w, widget_h))

    def but_connect(self): # 按钮绑定函数
        self.ui.pushButton.clicked.connect(lambda: self.execute('顺丰快递截图（后四位尾号验证模式）')) 
        self.ui.pushButton_5.clicked.connect(lambda: self.execute('顺丰快递截图（滑动图片验证模式）'))
        self.ui.pushButton_6.clicked.connect(lambda: self.execute('非顺丰快递截图（基于爱查快递）')) 
        self.ui.pushButton_7.clicked.connect(lambda: self.execute('非顺丰快递截图（基于菜鸟裹裹）')) 
        self.ui.pushButton_2.clicked.connect(lambda: self.execute('工商信息截图'))
        self.ui.action.triggered.connect(self.show_gxh) 
        self.ui.action_2.triggered.connect(self.show_kjz) 
        self.ui.action_3.triggered.connect(self.show_chat) 
        self.ui.action_4.triggered.connect(self.upadte_box) 
        self.ui.action_5.triggered.connect(self.jiaocheng) 
        self.ui.action_6.triggered.connect(self.setup_firefox) 

    def execute(self,title): # 执行子进程
        msg = u'正在运行【{}】，暂时不可进行其他操作！'.format(title)
        print(msg)
        self.statusBar().showMessage(msg)
        self.ui.centralwidget.setEnabled(False) # 锁定控件
        self.MyThread = MyThread(title) # 实例化自己建立的任务线程类
        self.MyThread.start() # 启动线程1
        self.MyThread.trigger.connect(self.recover) # 线程自定义信号连接的槽函数
    
    def recover(self,int): 
        if int == 1:
            ret = ctypes.windll.kernel32.TerminateThread(self.MyThread.handle, 0)
            print('终止线程', self.MyThread.handle, ret) 
            self.ui.centralwidget.setEnabled(True) # 恢复控件
            self.MyThread.quit()
            self.statusBar().showMessage("ok!日志文件已保存至Log文件夹！") # 恢复状态栏

class MyThread(QtCore.QThread): # 子进程
    trigger = QtCore.pyqtSignal(int)
    def __init__(self,title):
        super().__init__()
        self.stauts = 0 #判断子进程是否在运行
        self.title = title

    def run(self):
        try: # 获取当前进程的handle
            self.handle = ctypes.windll.kernel32.OpenThread(win32con.PROCESS_ALL_ACCESS, False, int(QtCore.QThread.currentThreadId()))
        except:
            print('get thread handle failed')
            print(traceback.format_exc())

        if self.stauts == 0:

            if self.title == '顺丰快递截图（后四位尾号验证模式）':
                a_sfkuaidi.Express()  # 把这个函数放入子线程 
            elif self.title == '顺丰快递截图（滑动图片验证模式）':
                b_sfkuaidi.Express() 
            elif self.title == '非顺丰快递截图（基于爱查快递）':
                c_fsfkuaidi.Express() 
            elif self.title == '非顺丰快递截图（基于菜鸟裹裹）':
                d_fsfkuaidi.Express() 
            elif self.title == '工商信息截图':
                e_tianyancha.main()

            self.stauts = 1 
        # fsf.Express()
        self.trigger.emit(self.stauts)
        
class dialog(QMainWindow): # 单继承子窗体
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui1 = Ui_dialog()
        self.ui1.setupUi(self)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    #实例化主窗体
    mainWindow = MyWindows()
    #实例化子窗体
    dialog=dialog()
    mainWindow.show()
    sys.exit(app.exec_())

